﻿using Microsoft.AspNetCore.Mvc;
using System;
using XCore.Logger;
using XCore.Authorization;
using SaaS.Core.Authorization;
using System.Linq;
using SaaS.Core;
using SaaS.Cache.Auths;
using XCore.Helper;
using XCore.Extensions;
using XCore.Domain.Dto;
using SaaS.Model.Enums;
using Web.System.Services.Systems;
using Web.System.Services.Auths;
using System.Collections;
using System.Collections.Generic;
using SaaS.Model.Dto.Systems;
using System.ComponentModel.DataAnnotations;

namespace Web.System.Controllers
{
    /// <summary>
    /// 帐号
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class AccountController : SystemControllerBase
    {
        private readonly AdminAppService _adminAppService;
        private readonly RoleAppService _roleAppService;
        private readonly SystemAuthCacheService _systemAuthCacheService;
        /// <summary>
        /// 构造
        /// </summary>
        public AccountController(
            AdminAppService adminAppService,
            RoleAppService roleAppService,
            SystemAuthCacheService systemAuthCacheService
            )
        {
            _adminAppService = adminAppService;
            _roleAppService = roleAppService;
            _systemAuthCacheService = systemAuthCacheService;
        }
        /// <summary>
        /// 登陆
        /// </summary>
        ///<param name="username">用户名</param>
        ///<param name="password">密码</param>
        /// <returns></returns>
        [HttpPost, DisableAuditing, Guest]
        public ActionResult Login([FromForm, Required]string username, [FromForm, Required]string password)
        {
            return Ok(_adminAppService.Login(username, password));
        }

        /// <summary>
        /// 用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Info()
        {
            SystemAdminModel admin = _systemAuthCacheService.GetSystemAdminInfo(Session);
            if (!admin) throw new SystemException("用户错误", SystemLoggerSource.Login);
            var permissions = admin.IsDefault ? PermissionNames.GetPermissions() : _systemAuthCacheService.GetRolePermission(admin.RoleId);
            return Ok(new
            {
                User = new
                {
                    admin.Name,
                    admin.UserName,
                    Avatar = admin.Avatar.GetUrl(),
                    admin.CreationTime
                },
                permissions
            });
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        ///<param name="password">新密码</param>
        ///<param name="confirmPassword">确认密码</param>
        ///<param name="usedpassword">旧密码</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ResetPwd([FromForm, Required]string password, [FromForm, Required]string confirmPassword, [FromForm, Required]string usedpassword)
        {
            if (!password.IsEqual(confirmPassword)) return Ok("密码不一致");
            return Ok(_adminAppService.ResetPwd(Session, password, usedpassword));
        }

        /// <summary>
        /// 上次图像
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Avatar()
        {
            string jsonString = HttpContext.Upload(CoreSetting.UtilServer.Url + "/icon");
            if (jsonString.IsNullOrWhiteSpace()) return Ok("上传失败");
            var result = jsonString.ToObject<Result>();
            if (_adminAppService.UploadAvatar(Session, result.Data.ToString()))
            {
                Logger.Log($"上传图像-{result.Data}", SystemLoggerSource.Admin);
                return Ok(result.Data);
            }
            return Ok("上传失败");
        }
        /// <summary>
        /// 获取系统权限
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Permission()
        {
            var menus = PermissionFinder.GetAllPermissionChildren(new MenuPermissionProvider());
            var permissions = PermissionFinder.GetAllPermissionChildren(new PermissionAuthorizationProvider(), new PermissionSystemProvider(), new PermissionBlogProvider());
            return Ok(new { Permissions = permissions, Menus = menus });
        }
        /// <summary>
        /// 初始化配置信息
        /// </summary>
        /// <returns></returns>
        [HttpGet, DisableAuditing, Guest]
        public ActionResult Init()
        {
            IDictionary<string, Dictionary<string, string>> enums = AssemblyHelper.GetAssemblyEnums();
            IDictionary<int, string> admins = _adminAppService.GetDictionary();
            IDictionary<int, string> roles = _roleAppService.GetDictionary();
            return Ok(new { enums, admins, roles });
        }
        /// <summary>
        /// 退出
        /// </summary>
        /// <returns></returns>
        [HttpPost, DisableAuditing]
        public ActionResult Logout()
        {
            _systemAuthCacheService.RemoveSystemToken(Session);
            return Ok(Logger.Log($"[{Session.UserName}]--退出成功", SystemLoggerSource.Login));
        }
    }
}